$(function () {
    renderUser()
  })
  
  async function getUserById() {
    let { id } = getParams() //{id:'40'} 对象解构
    if (!id) {
      return null
    }
    //准备参数
    let options = {
      url: 'http://146.56.230.35:3007/users/getUserById',
      type: 'GET',
      data: { id: parseInt(id) },
    }
    try {
      let res = await request(options)
      console.log(res)
      if (res.code !== 200) {
        alert(res.msg)
        return null
      }
      return res.user
    } catch (error) {
      return null
    }
  }
  
  async function renderUser() {
    let user = await getUserById()
    if (!user) {
      return
    }
    let userView = $('#userView')
    userView.empty()
    // let age = new Date().getFullYear() - new Date(user.birthday).getFullYear()
    let str = `
      <p><strong>用户编号：</strong><span>${user.userCode}</span></p>
      <p><strong>用户名称：</strong><span>${user.userName}</span></p>
      <p><strong>用户性别：</strong><span>${user.gender}</span></p>
      <p><strong>出生日期：</strong><span>${user.birthday}</span></p>
      <p><strong>用户电话：</strong><span>${user.phone}</span></p>
      <p><strong>用户地址：</strong><span>${user.address}</span></p>
      <p><strong>用户类别：</strong><span>${user.roleName}</span></p>
      <a href="userList.html">返回</a>
    `
    userView.append(str)
  }
  
  //获得url中的查询参数
  function getParams() {
    //?id=40&name=tom
    let search = location.search
    if (!search) {
      return null
    }
    search = search.substring(1)
    let index = search.indexOf('&')
    let object = {}
    if (index === -1) {
      let arr = search.split('=')
      object[arr[0]] = arr[1]
    } else {
      //id=40&name=tom--->arr=['id=40','name=tom']
      let arr = search.split('&')
      for (let i = 0; i < arr.length; i++) {
        //'id=40'
        let item = arr[i]
        //'id=40'--->['id','40']
        let array = item.split('=')
        object[array[0]] = array[1]
      }
    }
    return object
  }